'use strict';

angular.module('afasApp')
.directive('format', ['$filter', function ($filter) {
  return {
    require: '?ngModel',
    link: function (scope, elem, attrs, ctrl) {
      if (!ctrl) {
        return;
      }

      ctrl.$formatters.unshift(function (a) {
        console.log(a);
        return $filter(attrs.format)(ctrl.$modelValue);
      });

      ctrl.$parsers.unshift(function (viewValue) {
        var plainNumber = viewValue.replace(/[^\d|\-+|\.+]/g, '');
        elem.val($filter('number')(plainNumber));
        return plainNumber;
      });
    }
  };
}])
.directive('titleCase', ['$filter', '$parse', function ($filter, $parse) {
  return {
    require: '?ngModel',
    link: function (scope, elem, attrs, modelCtrl) {
      var capitalize = function(inputValue) {
        if (inputValue === undefined) { inputValue = ''; }
        var capitalized = inputValue.replace(/\w\S*/g, function(txt){
          return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
        });
        if(capitalized !== inputValue) {
          modelCtrl.$setViewValue(capitalized);
          modelCtrl.$render();
        }
        return capitalized;
      }
      var model = $parse(attrs.ngModel);
      modelCtrl.$parsers.push(capitalize);
      capitalize(model(scope));
  }
};
}]);
